﻿using Demo1.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Demo1.Controllers
{
    /// <summary>
    /// 认证测试
    /// </summary>
    [ApiController]
    [Route("[controller]")]
    public class JWTController : ControllerBase
    {

        private readonly IUserService _userService;
        private readonly ITokenService _tokenService;

        public JWTController(IUserService userService,
            ITokenService tokenService)
        {
            _userService = userService;
            _tokenService = tokenService;
        }

        [HttpGet,Authorize]
        public async Task<string> Get()
        {
            await Task.CompletedTask;

            return "Welcome";
        }

        /// <summary>
        /// 获取Token 默认用户 admin/123456
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpGet("getToken")]
        public async Task<string> GetTokenAsync(string name, string password)
        {
            var user = await _userService.LoginAsync(name, password);
            if (user == null)
                return "用户密码 不正确";
            //生成token
            var token = _tokenService.GetToken(user);

            var response = new
            {
                Status = true,
                Token = token,
                Type = "Bearer"
            };

            return JsonConvert.SerializeObject(response);
        }


    }
}
